//
// Created by 11510 on 2024/7/18.
//

#ifndef DAY80_DEMO3_CUSTOMWIDGET_H
#define DAY80_DEMO3_CUSTOMWIDGET_H
#include "CustomButton.h"
#include <QWidget>
#include <QApplication>
#include <QPushButton>
#include <QMouseEvent>
#include <QLabel>
#include <QEvent>
#include <QDebug>
#include <QVBoxLayout>

QT_BEGIN_NAMESPACE
namespace Ui { class CustomWidget; }
QT_END_NAMESPACE

class CustomWidget : public QWidget {
Q_OBJECT

public:
    explicit CustomWidget(QWidget *parent = nullptr) :
            QWidget(parent) {
        /* 不设置追踪需要按下鼠标才能移动 */
        setMouseTracking(true);

        QObject::connect(this, &CustomWidget::mouseMoved,
                         this, &CustomWidget::printMouse);

        A = new CustomButton("A", this);
        B = new CustomButton("B", A);
        C = new CustomButton("C", A);
        D = new CustomButton("D", A);
        E = new CustomButton("E", B);
        F = new CustomButton("F", B);

        this->setObjectName("W");

        // 设置按钮的层级关系
        A->setGeometry(0, 0, 600, 400);
        B->setGeometry(0, 0, 200, 200);
        C->setGeometry(0, 200, 200, 200);
        D->setGeometry(0, 400, 200, 200);
        E->setGeometry(0, 0, 100, 50);
        F->setGeometry(0, 150, 100, 50);

        // 安装事件过滤器
        this->installEventFilter(this);
        for (auto &btn: {A, B, C, D, E, F}) {
            btn->installEventFilter(this);
        }

    }

protected:
    bool eventFilter(QObject *obj, QEvent *event) override {
//        qDebug() << "objname = " << obj->objectName();
        if (event->type() == QEvent::MouseMove) {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            emit mouseMoved(mouseEvent->pos());

            if (obj == E || obj == F) {
                moveCAndD();
            }

        }
        return QWidget::eventFilter(obj, event);
    }

    bool event(QEvent *e) override {
        if (e->type() == QEvent::MouseButtonRelease) {
            qDebug() << objectName();
            return true;
        }
        /* 调父类才会调用handle */
        return QWidget::event(e);
    }

signals:
    void mouseMoved(const QPoint &pos);

private slots:
    void printMouse(const QPoint &pos) {
        qDebug() << "鼠标坐标" << pos;
    }

    void moveCAndD() {
        C->move(C->x() + 1, C->y() + 1);
        D->move(D->x() + 1, D->y() + 1);
    }
private:
    CustomButton *A, *B, *C, *D, *E, *F;
};


#endif //DAY80_DEMO3_CUSTOMWIDGET_H
